package com.aliwo.utils;

import com.aliwo.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;


/**
 * JWT工具类.
 *
 * @author xuyayuan
 * @date 2021/10/20 20:25
 */
public class JWTUtils {

    private static final Logger LOG = LoggerFactory.getLogger(JWTUtils.class);


    private static final String SUBJCT = "xuyy";

    /*
     * token过期时间, 1天
     */
    private static final long EXPIRE = 1000 * 60 * 60 * 24;

    /**
     * 密钥
     */
    private static final String APPSECRET = "xyy";

    /**
     * 功能描述: JWT生成token
     *
     * @param user
     * @return java.lang.String
     * @author xuyayuan
     */
    public static String geneJsonWebToken(User user) {
        if (null == user) {
            return null;
        }
        String token = Jwts.builder().setSubject(SUBJCT)
                .claim("id", user.getId())
                .claim("name", user.getName())
                .claim("img", user.getHeadImg())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, APPSECRET).compact();
        return token;
    }

    /**
     * 解密token的方法
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {
        try {
            final Claims claims = Jwts.parser().setSigningKey(APPSECRET)
                    .parseClaimsJws(token).getBody();
            return claims;
        } catch (Exception e) {
            LOG.error("token解密失败{}" + e);
            return null;
        }
    }


}
